package com.zzyl.intercept;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

//继承HandlerInterceptor类 重写前两个方法
public class UserTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //获取请求头中的token
        String token = request.getHeader(Constants.USER_TOKEN);
        //判断token是否为空
        if (ObjectUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //jwt是否正常解析
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);//jwt 解析
        if (ObjectUtil.isEmpty(claims)){
            throw  new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //获取用户数据
        String jsonStr = claims.get("currentUser", String.class);
        UserVo userVo = BeanUtil.toBean(jsonStr, UserVo.class);
        //从redis中获取url列表
        String urlsStr = redisTemplate.boundValueOps(CacheConstants.PUBLIC_ACCESS_URLS + userVo.getId()).get();
        List<String> urlList = JSONUtil.toList(urlsStr, String.class);
        //strings 当前登陆人的权限

        // 获取当前方法的请求方式和URI  POST/user/add
        // 请求方式
        String method = request.getMethod();
        // 请求URI
        String uri = request.getRequestURI();
        String url = method + uri;
        boolean isMatch = false;
        for (String s : urlList) {
            if (antPathMatcher.match(s, url)) {    //使用antPathMatcher匹配可以解决通配符的问题
                isMatch = true;
                break;
            }
        }
        if(!isMatch){  //for循环执行完成后没有匹配上权限
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        // 把用户存储到ThreadLocal中

        UserThreadLocal.setSubject(jsonStr);


        return true;


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.removeSubject();
    }
}
